package Controller;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginGeneric {
	public static void processLogin(
		HttpServletRequest request,
		HttpServletResponse response,
		LoginAuthenticator caller
	)
		throws ServletException, IOException
	{
		//Method Variables
		boolean loginSuccess = false;		//Whether Login was a success
		String generalMsg = "";					//Error Mesage for general
		String empIDMsg = "";						//Error MEssage for Employee ID
		String passwordMsg = "";				//Error MEssage for Password
		
		//See if Entries are correct
		String inEmployeeID = request.getParameter("EmployeeID");
		String inPassword = request.getParameter("Password");
		String inSubmit = request.getParameter("IsSubmit");
		
		if ( inSubmit == null) {				//If This was not a submitted form
			inEmployeeID = "";				//No Error messages give inEmployeeID a default value
		} else {									//Othewise this is a submitted form
			boolean startVerify = true;
			if (inEmployeeID == "") {		//If Empoyee ID is blank
				empIDMsg = "Please Enter an Employee ID";
				startVerify = false;
			} else if (! inEmployeeID.matches("[0-9]+") ) {
				empIDMsg = "Employee ID only has numbers";
				startVerify = false;				
			}
			if (inPassword == "") {			//If Password is blank
				passwordMsg = "Please Enter a Password";
				startVerify = false;
			}
			if ( startVerify )						//Otherwise both Employee ID and Password are filled
			{
				inEmployeeID = inEmployeeID.trim();
				inPassword = inPassword.trim();
				Object tempO = caller.authenticateUser(inEmployeeID, inPassword);
				if (tempO == null) {
					generalMsg = "Invalid Employee ID or Password!";
				} else {
					HttpSession thisSession = request.getSession(false);
					thisSession.setAttribute(caller.getSessionKey() , tempO);
					loginSuccess = true;
				}
			}
		}
		
		if (loginSuccess) {																		//If Login successful
			response.sendRedirect( caller.getSuccessPage() );							//Redirect here
		} else {																						//Otherwise Login failed, or this is first load
			request.setAttribute("CallerControl", caller.getCallerControl() );
			request.setAttribute("GeneralMsg", generalMsg);							//Store messages
			request.setAttribute("EmpIDInitialText", inEmployeeID);
			request.setAttribute("EmpIDMsg", empIDMsg);
			request.setAttribute("PasswordMsg", passwordMsg);	
			RequestDispatcher rd = request.getRequestDispatcher( caller.getCallerView() );	
			rd.forward(request,response);													//Dispatch to View
		}		
	}
}
